package homework.talkroom;


import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class Servers {
    private ServerSocket serverSocket;
    private Map<String,PrintWriter> allOut = new HashMap<>();
    public Servers(){
        try {
            System.out.println("正在启动服务端");
            serverSocket=new ServerSocket(9977);
            System.out.println("服务端启动完毕!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        try {
            while (true){
                System.out.println("正在等待服务端连接...");
                Socket socket=serverSocket.accept();
                System.out.println("一个客户端连接上了");

                ClientHandler handler = new ClientHandler(socket);
                Thread t = new Thread(handler);
                t.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private class ClientHandler implements Runnable{
        private Socket socket;
        private String host;//记录该客户端的IP地址
        private String nickName;//记录客户端昵称
       public ClientHandler(Socket socket){
           this.socket=socket;
           host=socket.getInetAddress().getHostAddress();//通过socket获取远端(客户端)计算机地址
       }
        public void run(){
            PrintWriter pw =null;
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                OutputStream out = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(out,StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(osw);
                pw = new PrintWriter(bw, true);

                nickName=br.readLine();//读取客户端发送过来的昵称
               synchronized (allOut){
                   allOut.put(nickName,pw);
               }
                sendMessageToAll("上线了,当前在线人数:"+allOut.size());//通知所有客户端,该用户上线了


                String message;
                while ((message=br.readLine())!=null){
                   if (message.startsWith("@")){
                       sendMessageToSomeone(message);
                   }else {
                       sendMessageToAll("说:"+message);
                   }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                synchronized (allOut) {
                    allOut.remove(nickName);
                }
                sendMessageToAll("下线了,当前人数:"+allOut.size());//通知所有客户端,该用户下线了
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        private void sendMessageToAll(String message){
            System.out.println(nickName+"["+host+"]"+message);
            synchronized (allOut){
                for(PrintWriter o : allOut.values()){
                    o.println(nickName+"["+host+"]"+message);
                }
            }
        }

        private void sendMessageToSomeone(String message){
           //message的样子:@范传奇:你好!
            if (message.matches("@.+:.+")){
                String tonickName = message.substring(1,message.indexOf(":"));

                if (allOut.containsKey(tonickName)){
                    PrintWriter pw = allOut.get(tonickName);
                    String toMessage = message.substring(message.indexOf(":") + 1);

                    pw.println(nickName+"悄悄对你说:"+toMessage);
                }else {
                    PrintWriter pw = allOut.get(nickName);
                    pw.println("该用户["+tonickName+"]不在线");
                }
            }else {
                PrintWriter pw = allOut.get(nickName);
                pw.println("私聊格式不正确!");
            }
        }
    }


    public static void main(String[] args) {
        Servers servers = new Servers();
        servers.start();
    }
}
